package com.kvest.fragmentsfinaltest.adapter;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.util.Log;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Kvest
 * Date: 25.03.13
 * Time: 21:36
 * To change this template use File | Settings | File Templates.
 */
public class MainAdapter extends FragmentStatePagerAdapter {
    private List<TabInfo> tabs;

    public MainAdapter(FragmentManager fragmentManager) {
        super(fragmentManager);

        tabs = new ArrayList<TabInfo>();
    }

    @Override
    public Fragment getItem(int i) {
        TabInfo tabInfo = tabs.get(i);
        try {
            Fragment fragment = tabInfo._class.newInstance();
            if (tabInfo.arguments != null) {
                fragment.setArguments(tabInfo.arguments);
            }
            return fragment;
        } catch (Exception exception) {
            return null;
        }
    }

    @Override
    public int getCount() {
        return tabs.size();
    }

    public void addFragment(Class<? extends Fragment> _class, Bundle arguments) {
        tabs.add(new TabInfo(_class, arguments));

        notifyDataSetChanged();
    }

    public void addFragment(Class<? extends Fragment> _class) {
        addFragment(_class, null);
    }

    private static class TabInfo {
        public TabInfo(Class<? extends Fragment> _class, Bundle arguments) {
            this._class = _class;
            this.arguments = arguments;
        }

        public Class<? extends Fragment> _class;
        public Bundle arguments;
    }
}
